//
//  NRWLoginVC.m
//  NRWMall
//
//  Created by 邢毅 on 2018/6/22.
//  Copyright © 2018年 com.anpxd. All rights reserved.
//

#import "NRWLoginVC.h"
#import "NRWLoginView.h"
#import "NRWWebViewController.h"
#import "NRWLoginApi.h"
#import "NRWUserInfoModel.h"
#import "NRWSendCodeApi.h"

@interface NRWLoginVC ()<UITextFieldDelegate>

@property (strong, nonatomic) NRWSendCodeApi *sendCodeApi;

@property (strong, nonatomic) NRWLoginApi *loginApi;

@property (strong, nonatomic) NSTimer *timer;

@property (assign, nonatomic) NSInteger timerTimes;

@end

@implementation NRWLoginVC
{
    UIView *_loginMainView;
    UILabel *_titleLabel;
    UITextField *_userNameTextField;
    UITextField *_passWordTextField;
    UIButton *_codeBtn;
    UIButton *_deleteBtn;
    UILabel *_agreementlabel;
    UIButton *_loginBtn;
    UIButton *_closeBtn;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationView.hidden = YES;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [[tap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        [self.view endEditing:YES];
    }];
    [self.view addGestureRecognizer:tap];
    
    [self setupUI];
    
    [self layoutUI];
    
}

- (void)setupUI {
    
    _loginMainView = DPView().setBackgroundColor([UIColor whiteColor]);
    _loginMainView.layer.cornerRadius = 10;
    
    _titleLabel = DPLabel()
    .setText(@"登录")
    .setTextColor(getColor(@"#333333"))
    .setFont(getThemeFont(17));
    
    _codeBtn = DPButton()
    .setNormalTitle(@"获取验证码")
    .setNormalTitleColor(getColor(@"FF5F00"))
    .setTitleColor(getColor(@"#B3B3B3"), UIControlStateDisabled)
    .setTitleFont(getThemeFont(14))
    .addClickAction(self, @selector(getCodeBtnDidClick:));
    _codeBtn.enabled = NO;
    
    _deleteBtn = DPButton()
    .setNormalImage(getImage(@"login_clear"))
    .addClickAction(self, @selector(deleteBtnDidClick:));
    _deleteBtn.hidden = YES;
    
    _userNameTextField = DPTextField()
    .setPlaceholder(@"请输入您的手机号")
    .setFont(getThemeFont(15))
    .setTextColor(getColor(@"333333"))
    .setKeyboardType(UIKeyboardTypeNumberPad)
    .setLeftView(DPView().setFrame(CGRectMake(0, 0, 10, 10)), UITextFieldViewModeAlways);
    [_userNameTextField addTarget:self action:@selector(inputTextFiledDidChange:) forControlEvents:UIControlEventEditingChanged];
    _userNameTextField.delegate = self;
    _userNameTextField.layer.borderColor = getColor(@"999999").CGColor;
    _userNameTextField.layer.borderWidth = 0.5;
    
    _userNameTextField
    .addSubview(_codeBtn)
    .addSubview(_deleteBtn);
    
    _passWordTextField = DPTextField()
    .setPlaceholder(@"请输入短信验证码")
    .setFont(getThemeFont(15))
    .setTextColor(getColor(@"333333"))
    .setClearButtonMode(UITextFieldViewModeWhileEditing)
    .setKeyboardType(UIKeyboardTypeNumberPad)
    .setLeftView(DPView().setFrame(CGRectMake(0, 0, 10, 10)), UITextFieldViewModeAlways);
    [_passWordTextField addTarget:self action:@selector(inputTextFiledDidChange:) forControlEvents:UIControlEventEditingChanged];
    _passWordTextField.layer.borderColor = getColor(@"999999").CGColor;
    _passWordTextField.layer.borderWidth = 0.5;
    
    //改变系统cleanBtn的样子, 样式统一
    UIButton *button = [_passWordTextField valueForKey:@"_clearButton"];
    [button setImage:[UIImage imageNamed:@"login_clear"] forState:UIControlStateNormal];
    
    _closeBtn = [[UIButton alloc] init];
    [_closeBtn setImage:getImage(@"login_close") forState:UIControlStateNormal];
    [_closeBtn addTarget:self action:@selector(closeBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:@"登录即视为同意用户使用协议&隐私协议"];
    [att setAttributes:@{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle], NSForegroundColorAttributeName: mainColor()} range:NSMakeRange(7, 6)];
    [att setAttributes:@{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle], NSForegroundColorAttributeName: mainColor()} range:NSMakeRange(14, 4)];
    _agreementlabel = DPLabel()
    .setTextColor(mainFontColor())
    .setFont(getThemeFont(12));
    _agreementlabel.userInteractionEnabled = YES;
    _agreementlabel.attributedText = att;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [_agreementlabel addGestureRecognizer:tap];
    @weakify(self)
    [[tap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        @strongify(self)
        CGPoint point = [x locationInView:self->_agreementlabel];
        CGFloat index = self->_agreementlabel.viewWidth / self->_agreementlabel.text.length;
        NRWWebViewController *vc = [[NRWWebViewController alloc] init];
        if (point.x >= 7 * index && point.x <= 13 * index) {
            
            vc.url = [[[NSBundle mainBundle] URLForResource:@"userProtocol.html" withExtension:nil] absoluteString];
            vc.navigationView.title = @"用户使用协议";
        } else if (point.x >= 14 * index) {
            vc.url = [[[NSBundle mainBundle] URLForResource:@"privacyPolicy.html" withExtension:nil] absoluteString];
            vc.navigationView.title = @"隐私协议";
        }
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    _loginBtn = DPButton()
    .setNormalTitle(@"登  录")
    .setNormalTitleColor(getColor(@"FFFFFF"))
    .addClickAction(self, @selector(loginBtnDidClick:));
    [_loginBtn setBackgroundImage:getImage(@"login_login_e") forState:UIControlStateNormal];
    
    _loginMainView.addSubview(_titleLabel)
    .addSubview(_userNameTextField)
    .addSubview(_passWordTextField)
    .addSubview(_agreementlabel)
    .addSubview(_loginBtn)
    .addSubview(_closeBtn);
    
    _userNameTextField.addSubview(_codeBtn);
    
    self.view.addSubview(_loginMainView);
    
}

- (void)layoutUI {
    
    [_loginMainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view).multipliedBy(0.915);
        make.center.equalTo(self.view);
        make.height.equalTo(@275);
    }];
    
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self->_loginMainView.mas_top).offset(23);
        make.centerX.equalTo(self->_loginMainView);
        make.height.equalTo(@16);
    }];
    
    [_userNameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self->_titleLabel.mas_bottom).offset(19);
        make.left.equalTo(self->_loginMainView.mas_left).offset(29);
        make.right.equalTo(self->_loginMainView.mas_right).offset(-29);
        make.height.equalTo(@45);
    }];
    
    [_codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self->_userNameTextField.mas_right).offset(-8);
        make.top.bottom.equalTo(self->_userNameTextField);
    }];
    
    [_deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self->_codeBtn.mas_left).offset(-8);
        make.top.bottom.equalTo(self->_userNameTextField);
    }];
    
    [_passWordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self->_userNameTextField.mas_bottom).offset(20);
        make.left.right.equalTo(self->_userNameTextField);
        make.height.equalTo(@45);
    }];
    
    [_agreementlabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self->_passWordTextField.mas_left);
        make.top.equalTo(self->_passWordTextField.mas_bottom).offset(9);
    }];
    
    [_loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self->_passWordTextField);
        make.top.equalTo(self->_passWordTextField.mas_bottom).offset(54);
        make.height.equalTo(@35);
    }];
    
    [_closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.equalTo(@44);
        make.top.right.equalTo(self->_loginMainView);
    }];
}

#pragma mark - setupTimer
- (void)setupTimer:(NSInteger)time {
    
    self.timerTimes = time;
    [_codeBtn setTitle:[NSString stringWithFormat:@"%lds重新获取", (long)self.timerTimes] forState:UIControlStateDisabled];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)timerAction {
    
    self.timerTimes -= 1;
    
    if (self.timerTimes < 0) {
        _codeBtn.enabled = YES;
        [self.timer invalidate];
        self.timer = nil;
        return;
    }
    
    [_codeBtn setTitle:[NSString stringWithFormat:@"%lds重新获取", (long)self.timerTimes] forState:UIControlStateDisabled];
}

#pragma mark - NetworkDelegate
- (void)requestFinished:(__kindof YTKBaseRequest *)request {
    
    if (request == self.sendCodeApi) {
        
        if ([self.sendCodeApi.responseObject[@"code"] integerValue] == 1) {
            [self setupTimer:60];
            [NRWMessageHUD showMessage:@"验证码发送成功" forTime:1.5 withRemindId:remindSuccess];
        } else {
            [NRWMessageHUD showMessage:self.sendCodeApi.responseObject[@"msg"] forTime:1.5 withRemindId:remindFail];
        }
    } else if (request == self.loginApi) {
        
        if ([self.loginApi.responseObject[@"code"] integerValue] == 1) {
            
            [NRWUserInfoModel setValueForUserInfoDict:self.loginApi.responseObject[@"result"]];
            [[NSNotificationCenter defaultCenter] postNotificationName:userLoginSuccess object:self.type];
            [NRWMessageHUD showMessage:@"登录成功" forTime:1.5 withRemindId:remindSuccess animationCompleted:^{
                
//                [self dismiss];
                
                if (self.loginSuccessBlock) {
                    self.loginSuccessBlock();
                }
            }];
        } else {
            [NRWMessageHUD showMessage:self.loginApi.responseObject[@"msg"] forTime:1.5 withRemindId:remindFail];
        }
    }
}

- (void)requestFailed:(__kindof YTKBaseRequest *)request {
    
    
}

#pragma mark - EventAction
- (void)getCodeBtnDidClick:(UIButton *)sender {
    
    _codeBtn.enabled = NO;
    self.sendCodeApi.userMobile = _userNameTextField.text;
    [self.sendCodeApi start];
}

- (void)agreementBtnDidClick:(UIButton *)sender {
    
    sender.selected = !sender.selected;
}

- (void)loginBtnDidClick:(UIButton *)sender {
    
    if (_userNameTextField.text.length < 11) {
        [NRWMessageHUD showMessage:@"请输入正确的手机号码" forTime:1.5];
        return;
    }
    
    if (_passWordTextField.text.length < 6) {
        [NRWMessageHUD showMessage:@"请输入正确验证码" forTime:1.5];
        return;
    }
    
    self.loginApi.userMobile = _userNameTextField.text;
    self.loginApi.validateCode = _passWordTextField.text;
    [self.loginApi start];
}

- (void)closeBtnDidClick:(UIButton *)sender {
    
//    [self dismiss];
}

- (void)deleteBtnDidClick:(UIButton *)sender {
    
    _userNameTextField.text = nil;
}

- (void)inputTextFiledDidChange:(UITextField *)sender {
    
    if (sender == _userNameTextField) {
        _deleteBtn.hidden = !_userNameTextField.text.length;
        if (_userNameTextField.text.length > 11) {
            _userNameTextField.text = [_userNameTextField.text substringToIndex:11];
        }
        _codeBtn.enabled = _userNameTextField.text.length == 11;
    } else {
        if (_passWordTextField.text.length > 6) {
            _passWordTextField.text = [_passWordTextField.text substringToIndex:6];
        }
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    if (textField == _userNameTextField) {
        _deleteBtn.hidden = YES;
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
    //由于addSubView 所以需要把按钮放到上面来 不然点击不到
    [textField bringSubviewToFront:_deleteBtn];
    [textField bringSubviewToFront:_codeBtn];
}


@end
